package com.jrh.common.img;

import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 图片剪切工具
 * 
 * @author jasen.hsu.cn@gmail.com 2012-7-21 下午9:00:55
 */
public class ImageCuter {

    private static final Logger log = LoggerFactory.getLogger(ImageCuter.class);

    /**
     * 裁剪,输出的图片格式会按照输入源文件的格式为准
     * 
     * @param inputImgFile 源图
     * @param ouputImgFile 目标图
     * @param x 起点x坐标
     * @param y 起点y坐标
     * @param width 宽
     * @param height 高
     * @return
     */
    public static boolean cut(String inputImgFile, String ouputImgFile, int x, int y, int width, int height) {
        try {
            File inputFile = new File(inputImgFile);
            if (!inputFile.exists()) {
                log.error("img file is not exists");
                return false;
            }
            if (!ImageFileUtil.isImage(inputFile)) {
                log.error("not img file");
                return false;
            }
            BufferedImage inputBi = ImageIO.read(inputFile);
            BufferedImage outputBi = inputBi.getSubimage(x, y, width, height);
            return ImageIO.write(outputBi, ImageFileUtil.getImageFileType(inputFile), new File(ouputImgFile));
        } catch (Exception e) {
            log.error("cut img error:", e);
        }
        return false;
    }
}
